<template>
  <el-dialog
    title="上传文件"
    :close-on-click-modal="false"
    @close="closeHandle"
    :visible.sync="visible"
    append-to-body>
    <el-upload
      :action="url"
      :auto-upload="false"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      :limit="1"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只支持xls,xlsx格式</div>
    </el-upload>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="download">模板下载</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        myHeaders: {},
        visible: false,
        url: '',
        num: 0,
        successNum: 0,
        fileList: []
      }
    },
    methods: {
      init () {
        this.myHeaders = { 'token': this.$cookie.get('token') }
        this.url = this.$http.BASE_URL + `/mall/shops/uploadSave?token=${this.$cookie.get('token')}`
        this.visible = true
      },
      // 上传之前
      beforeUploadHandle (file) {
        console.log(file.type)
        if (file.type !== 'application/vnd.ms-excel' && file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          this.$message.error('只支持xls,xlsx格式！')
          return false
        }
        this.num++
      },
      submitUpload () {
        this.$children[0].$children[0].submit()
      },
      download () {
        const { export_json_to_excel } = require('../../../excel/Export2Excel')
        const tHeader = ['店铺名称', '店铺类型，1，普通店铺，2支行', '总店分店，1总店2分店', '父店id/支行id', '联系电话','店铺详细地址','经度','纬度'] // 对应表格输出的title
        const filterVal = ['cardSn', 'type','level','parentId','telephone','details','latitude','longitude'] // 对应表格输出的数据
        const exceldata = this.formatJson(filterVal, [{'cardSn': '名称', 'type': 1,'level':2,'parentId':'','telephone':'13333333333','details':'','latitude':'','longitude':''}])
        export_json_to_excel([tHeader], [exceldata], '店铺导入模版')// 对应下载文件的名字
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      // 上传成功
      successHandle (response, file, fileList) {
        this.fileList = []
        this.successNum++
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm('操作成功, 是否继续操作?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(() => {
              this.visible = false
            })
          }
        } else {
          this.$message.error(response.msg)
        }
      },
      // 弹窗关闭时
      closeHandle () {
        this.fileList = []
        this.$emit('refreshDataList')
      }
    }
  }
</script>
